package cn.edu.bit.mm.service;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.edu.bit.dto.WebPage;
import cn.edu.bit.req.Request;

@Component
public class SingleDaemonSearchService implements SearchService {

	@Autowired
	private Integer port;
	@Autowired
	private String ip;
	private int totalPage;
	
	public SingleDaemonSearchService(){}
	
	
	public SingleDaemonSearchService(String ip,int port){
		this.ip = ip;
		this.port = port;
	}	
	
	public WebPage[] getSearchResult(String keyWord, int pageNumber) {
		
		Socket socket = null;
		ObjectInputStream reader = null;
		ObjectOutputStream writer = null;		
		WebPage[] result = null;
		try {
			socket = new Socket(ip,port);
			reader = new ObjectInputStream(socket.getInputStream());
			writer = new ObjectOutputStream(socket.getOutputStream());
			Request req = new Request(pageNumber,keyWord);
			writer.writeObject(req);			
			if(pageNumber==1){
				totalPage = reader.readInt();				
			}
			result = (WebPage[])reader.readObject();			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{			
			try {
				if(reader!=null){
					reader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					if(writer!=null){
						writer.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					if(socket!=null){
						try {
							socket.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			
		}
		return result;
	}
	
	public int getTotalPage() {
		return totalPage;
	}

	public boolean checkKeyWord(String keyWord) {		
		return (!(keyWord==null||keyWord.trim().equals("")));
	}

	public int computeQueryPage(String pageNumberReq) {
		if(pageNumberReq==null){
			return 1;
		}		
		return Integer.valueOf(pageNumberReq);		
	}	
	
}
